#!/bin/bash

# OCH-MRCP 高并发优化启动脚本
# 包含JVM性能调优参数

# 应用配置
APP_NAME="och-mrcp"
APP_JAR="target/och-mrcp-0.0.1-SNAPSHOT.jar"
APP_MAIN="com.och.mrcp.OchMrcpApplication"
JAVA_OPTS=""

# JVM内存配置（根据服务器配置调整）
HEAP_SIZE="4g"              # 堆内存大小
HEAP_MIN="2g"               # 最小堆内存
NEW_SIZE="1g"               # 新生代大小
META_SIZE="256m"            # 元空间大小

# JVM性能优化参数
JVM_OPTS=""

# 内存设置
JVM_OPTS="$JVM_OPTS -Xms$HEAP_MIN"
JVM_OPTS="$JVM_OPTS -Xmx$HEAP_SIZE"
JVM_OPTS="$JVM_OPTS -Xmn$NEW_SIZE"
JVM_OPTS="$JVM_OPTS -XX:MetaspaceSize=$META_SIZE"
JVM_OPTS="$JVM_OPTS -XX:MaxMetaspaceSize=512m"

# G1垃圾收集器配置（推荐用于低延迟应用）
JVM_OPTS="$JVM_OPTS -XX:+UseG1GC"
JVM_OPTS="$JVM_OPTS -XX:MaxGCPauseMillis=200"
JVM_OPTS="$JVM_OPTS -XX:G1HeapRegionSize=16m"
JVM_OPTS="$JVM_OPTS -XX:G1NewSizePercent=30"
JVM_OPTS="$JVM_OPTS -XX:G1MaxNewSizePercent=40"
JVM_OPTS="$JVM_OPTS -XX:G1MixedGCCountTarget=8"
JVM_OPTS="$JVM_OPTS -XX:InitiatingHeapOccupancyPercent=45"

# JIT编译器优化
JVM_OPTS="$JVM_OPTS -XX:+TieredCompilation"
JVM_OPTS="$JVM_OPTS -XX:TieredStopAtLevel=4"
JVM_OPTS="$JVM_OPTS -XX:CompileThreshold=10000"

# 字符串优化
JVM_OPTS="$JVM_OPTS -XX:+UseStringDeduplication"
JVM_OPTS="$JVM_OPTS -XX:+OptimizeStringConcat"

# 锁优化
JVM_OPTS="$JVM_OPTS -XX:+UseBiasedLocking"
JVM_OPTS="$JVM_OPTS -XX:+UseThreadPriorities"
JVM_OPTS="$JVM_OPTS -XX:+DoEscapeAnalysis"

# 网络和I/O优化
JVM_OPTS="$JVM_OPTS -Djava.net.preferIPv4Stack=true"
JVM_OPTS="$JVM_OPTS -Dio.netty.recycler.maxCapacityPerThread=0"
JVM_OPTS="$JVM_OPTS -Dio.netty.leakDetection.level=simple"

# 安全随机数优化
JVM_OPTS="$JVM_OPTS -Djava.security.egd=file:/dev/./urandom"

# GC日志配置
GC_LOG_DIR="logs/gc"
mkdir -p $GC_LOG_DIR
JVM_OPTS="$JVM_OPTS -XX:+PrintGC"
JVM_OPTS="$JVM_OPTS -XX:+PrintGCDetails"
JVM_OPTS="$JVM_OPTS -XX:+PrintGCTimeStamps"
JVM_OPTS="$JVM_OPTS -XX:+PrintGCApplicationStoppedTime"
JVM_OPTS="$JVM_OPTS -Xloggc:$GC_LOG_DIR/gc_%p_%t.log"
JVM_OPTS="$JVM_OPTS -XX:+UseGCLogFileRotation"
JVM_OPTS="$JVM_OPTS -XX:NumberOfGCLogFiles=5"
JVM_OPTS="$JVM_OPTS -XX:GCLogFileSize=100M"

# OOM处理
JVM_OPTS="$JVM_OPTS -XX:+HeapDumpOnOutOfMemoryError"
JVM_OPTS="$JVM_OPTS -XX:HeapDumpPath=logs/heapdump/"
mkdir -p logs/heapdump/

# JFR性能分析（生产环境可选）
if [ "$ENABLE_JFR" = "true" ]; then
    JVM_OPTS="$JVM_OPTS -XX:+FlightRecorder"
    JVM_OPTS="$JVM_OPTS -XX:StartFlightRecording=duration=60s,filename=logs/jfr/startup.jfr"
    mkdir -p logs/jfr/
fi

# 应用参数
APP_OPTS=""
APP_OPTS="$APP_OPTS --spring.profiles.active=prod"
APP_OPTS="$APP_OPTS --server.port=8080"
APP_OPTS="$APP_OPTS --logging.file.path=logs/"

# 检查Java版本
java_version=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
echo "Java version: $java_version"

if [[ $java_version < "17" ]]; then
    echo "Warning: Java 17 or higher is recommended for optimal performance"
fi

# 检查系统资源
echo "System Info:"
echo "  CPU cores: $(nproc)"
echo "  Memory: $(free -h | grep Mem | awk '{print $2}')"
echo "  Disk space: $(df -h . | tail -1 | awk '{print $4}')"

# 网络优化建议
echo "Network Optimization Tips:"
echo "  - Consider increasing net.core.somaxconn (e.g., 65535)"
echo "  - Consider increasing net.core.netdev_max_backlog (e.g., 30000)"
echo "  - Consider tuning TCP buffer sizes"

# 启动应用
echo "Starting $APP_NAME with optimized JVM settings..."
echo "JVM Options: $JVM_OPTS"
echo "App Options: $APP_OPTS"

# 创建日志目录
mkdir -p logs/

# 启动命令
if [ -f "$APP_JAR" ]; then
    nohup java $JVM_OPTS -jar $APP_JAR $APP_OPTS > logs/console.log 2>&1 &
    PID=$!
    echo $PID > $APP_NAME.pid
    echo "Application started with PID: $PID"
    echo "Console log: logs/console.log"
    echo "GC log: $GC_LOG_DIR/"
else
    echo "Error: JAR file not found: $APP_JAR"
    echo "Please run 'mvn clean package' first"
    exit 1
fi

# 等待应用启动
echo "Waiting for application to start..."
sleep 10

# 检查应用状态
if kill -0 $PID 2>/dev/null; then
    echo "Application is running successfully"
    echo "Health check: http://localhost:8080/actuator/health"
    echo "Metrics: http://localhost:8080/actuator/metrics"
else
    echo "Application failed to start. Check logs/console.log for details"
    exit 1
fi
